package controller.group_management;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.trek2000.android.enterprise.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import adapter.group_management.PhotoAndVDOTabInGroupFeedFragmentAdapter;
import define.API;
import define.Key;
import model.group_management.PhotoAndVDOTabInGroupFeedItem;
import model.group_management.ShotOfPhotoAndVDOTabInGroupFeedItem;
import ui.fragment.group_management.PhotoAndVDOTabInGroupFeedFragment;
import utils.Utils;

/**
 * Created by trek2000 on 19/8/2014.
 */
public class PhotoAndVDOTabInGroupFeedFragmentAsync extends AsyncTask<String, Void, Boolean> {

    /**
     * String section
     */
    private String ADDED_DATE = "";
    private int number_of_photos = 0;
    private int number_of_videos = 0;
    private String TITLE = "";
    private String SPLASH = "";
    private String UPLOAD_TIME = "";
    private String OBJECT = "";
    private String PREVIEW_MEDIUM = "";
    private int content_type = 0;
    private int shot_id = 0;
    private long global_shot_id = 0;
    private String OWNER_NAME = "" ;

    private String ERROR = "";
    private String STATUS = "";
//    public  static int counter = 0;

    /**
     * View section
     */

    /**
     * The others section
     */
    private Context mContext;
    public static ArrayList <PhotoAndVDOTabInGroupFeedItem> mAlPhotoAndVDOTabInGroupFeed = new ArrayList<>();
//    public static ArrayList <Long> mAlGroupId = new ArrayList<>();

    public PhotoAndVDOTabInGroupFeedFragmentAsync(Context context) {
        this.mContext = context;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        return getData(params);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //TODO clear, check id unique later
        if (!mAlPhotoAndVDOTabInGroupFeed.isEmpty())
            mAlPhotoAndVDOTabInGroupFeed.clear();

    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        // hide waiting dialog
        Utils.hideWaitingDialog();

        if (!result) {
            Toast.makeText(mContext, ERROR ,
                    Toast.LENGTH_SHORT).show();
        } else {
            PhotoAndVDOTabInGroupFeedFragment.photoAndVDOTabInGroupFeedFragmentAdapter = new PhotoAndVDOTabInGroupFeedFragmentAdapter(mContext,
                    R.layout.simple_list_item_photo_and_vdo_tab_in_group_feed_fragment,
                    mAlPhotoAndVDOTabInGroupFeed);
            PhotoAndVDOTabInGroupFeedFragment.mLvInPhotoAndVDOInGroupFeedFragment.setAdapter(
                    PhotoAndVDOTabInGroupFeedFragment.photoAndVDOTabInGroupFeedFragmentAdapter);

            //display view
            PhotoAndVDOTabInGroupFeedFragment.displayViewForPhotoAndVDOTabInGroupFeedFragment(mAlPhotoAndVDOTabInGroupFeed);
        }
    }

    /**
     * Basic methods
     */
    private boolean getData(String[] params) {
        HttpPost mHttpPost = new HttpPost(API.GET_PHOTOS_AND_VIDEOS_FROM_GROUP);
        List<NameValuePair> mListValues = new ArrayList<NameValuePair>();
        /**
         * user_Name
         * password
         * device_token
         * device_OS
         */
        mListValues.add(new BasicNameValuePair(Key.USER_GLOBAL_ID, params[0]));
        mListValues.add(new BasicNameValuePair(Key.ACCESS_TOKEN, params[1]));
        mListValues.add(new BasicNameValuePair(Key.COMPANY_ID, params[2]));
        mListValues.add(new BasicNameValuePair(Key.GROUP_ID, params[3]));
        mListValues.add(new BasicNameValuePair(Key.ACCESS_MODE, params[4]));
        mListValues.add(new BasicNameValuePair(Key.USER_COMPANY_ID, params[5]));
        mListValues.add(new BasicNameValuePair(Key.PAGE_INDEX, params[6]));

        try {
            mHttpPost.setEntity(new UrlEncodedFormEntity(mListValues));
            HttpParams mHttpParams = new BasicHttpParams();

            int TIMEOUT_CONNECTION = 30000;
            int TIMEOUT_SOCKET = 30000;

            HttpConnectionParams.setConnectionTimeout(
                    mHttpParams, TIMEOUT_CONNECTION);
            HttpConnectionParams.setSoTimeout(mHttpParams, TIMEOUT_SOCKET);
            HttpClient mHttpclient = new DefaultHttpClient(mHttpParams);
            HttpResponse mHttpResponse;
            mHttpResponse = mHttpclient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            String XML = EntityUtils.toString(mHttpEntity);

            Log.i("", PhotoAndVDOTabInGroupFeedFragmentAsync.class.getSimpleName() + " " + XML);

            JSONObject mJoXml = new JSONObject(XML);
            //get string in mJoXml
            STATUS = mJoXml.getString(Key.STATUS);
            if (STATUS.equals(mContext.getString(R.string.success_))) {
                //get number of shots
//                counter = mJoXml.getInt(Key.COUNTER);
                //get mJaGroups in mJoXml
                JSONArray mJaGroups = mJoXml.getJSONArray(Key.COMPANY_SHOTS_GROUPS);
                if (!"[]".equals(mJaGroups.toString())) {
                    //get mJoGroups from mJaGroups
                    for (int i = 0; i < mJaGroups.length(); i++) {
                        JSONObject mJoGroups = mJaGroups.getJSONObject(i);
                        //get string from mJoGroups
                        ADDED_DATE = mJoGroups.getString(Key.ADDED_DATE);
                        number_of_photos = mJoGroups.getInt(Key.NUMBER_OF_PHOTOS);
                        number_of_videos = mJoGroups.getInt(Key.NUMBER_OF_VIDEOS);
                        ArrayList <ShotOfPhotoAndVDOTabInGroupFeedItem> mAlShotOfPhotoAndVDOTabInGroupFeedItem = new ArrayList<>();
                        // get mJaShots from mJoGroups
                        JSONArray mJaShots = mJoGroups.getJSONArray(Key.SHOTS);
                        if (!"[]".equals(mJaShots.toString())) {
                            //get mJoShots from mJaShots
                            for (int j = 0; j < mJaShots.length(); j++) {
                                JSONObject mJoShots = mJaShots.getJSONObject(j);
                                TITLE = mJoShots.getString(Key.TITLE);
                                SPLASH = mJoShots.getString(Key.SPLASH);
                                UPLOAD_TIME = mJoShots.getString(Key.UPLOAD_TIME);
                                OBJECT = mJoShots.getString(Key.OBJECT);
                                PREVIEW_MEDIUM = mJoShots.getString(Key.PREVIEW_MEDIUM);
                                content_type = mJoShots.getInt(Key.CONTENT_TYPE);
                                shot_id = mJoShots.getInt(Key.SHOT_ID);
                                global_shot_id = mJoShots.getLong(Key.GLOBAL_SHOT_ID);
                                OWNER_NAME = mJoShots.getString(Key.OWNER_NAME);
                                ShotOfPhotoAndVDOTabInGroupFeedItem shotOfPhotoAndVDOTabInGroupFeedItem = new ShotOfPhotoAndVDOTabInGroupFeedItem(
                                        TITLE, SPLASH, UPLOAD_TIME,
                                        OBJECT, PREVIEW_MEDIUM, content_type,
                                        shot_id, global_shot_id, OWNER_NAME,
                                        false);
                                // TODO check duplicate at here
                                mAlShotOfPhotoAndVDOTabInGroupFeedItem.add(shotOfPhotoAndVDOTabInGroupFeedItem);
                            }
                        }
                        PhotoAndVDOTabInGroupFeedItem photoAndVDOTabInGroupFeedItem  = new PhotoAndVDOTabInGroupFeedItem(
                                ADDED_DATE, number_of_photos, number_of_videos,
                                mAlShotOfPhotoAndVDOTabInGroupFeedItem
                        );
                        // TODO check duplicate at here
                        mAlPhotoAndVDOTabInGroupFeed.add(photoAndVDOTabInGroupFeedItem);
                    }
                }
                return  true;
            } else if (STATUS.equals(mContext.getString(R.string.error))) {
                ERROR = mJoXml.getString(Key.ERROR);
                return false;
            }
        } catch (ClassCastException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}